<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <Header :title="'返回'" :subTitle="subTitle" :hasBackPath="true" @headerBack="$router.back()"></Header>
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="rules"
        :colon="false"
        :labelCol="{ lg: { span: 3 }, sm: { span: 4 } }"
        :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
      >
        <a-form-model-item label=" " >
          <a-form-model-item v-if="type > 1" :label="type == 2 ? '作废原因' : '延期原因'" prop="reason" :labelCol="{ span: 24 }">
            <a-textarea
              allowClear
              v-model="form.reason"
              placeholder="请说明原因"
            />
          </a-form-model-item>
          <a-button type="primary" icon="plus" @click="handleAdd">添加新的批次</a-button>
          <div class="item" v-for="(record, index) in form.relationList" :key="index">
            <div style="display: flex;justify-content: space-between;">
              <h3>批次{{index+1}}</h3>
              <a-popconfirm title="请确认是否删除本批次信息？" @confirm="handleDelet(index)">
                <a-button>删除本批次</a-button>
              </a-popconfirm>
            </div>
            <a-form-model-item label="优惠券号（起始）" labelAlign="left" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :prop="`relationList.${index}.vouchersNoStart`" :rules="[
                  { required: true, message: '请输入优惠券号', trigger: 'blur' },
                  {
                    validator: (rule, value, callback) => {
                      const reg =  /^[0-9a-zA-Z\-]*$/g
                      if (reg.test(value)) {
                        callback()
                      } else {
                        return callback('请输入正确的格式')
                      }
                    },
                    trigger: 'blur'
                  }
                ]">
              <a-input v-model.trim="record.vouchersNoStart" placeholder="请输入优惠券号" allowClear style="width: 100%;"  />
            </a-form-model-item>
            <a-form-model-item label="优惠券号（结束）" labelAlign="left" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :prop="`relationList.${index}.vouchersNoEnd`" :rules="[
                  { required: true, message: '请输入优惠券号', trigger: 'blur' },
                  {
                    validator: (rule, value, callback) => {
                      const reg =  /^[0-9a-zA-Z\-]*$/g
                      if (reg.test(value)) {
                        callback()
                      } else {
                        return callback('请输入正确的格式')
                      }
                    },
                    trigger: 'blur'
                  }
                ]">
              <a-input v-model.trim="record.vouchersNoEnd" placeholder="请输入优惠券号" allowClear style="width: 100%;"  />
            </a-form-model-item>
          </div>
          <!-- <div style="text-decoration: underline;">当前共成功添加x个券号！</div> -->
          <a-form-model-item labelAlign="left" class="show-title" v-if="type==3" :labelCol="{lg: { span: 4 }, sm: { span: 5 }}" label="有效期延至" prop="time" >
            <a-date-picker
              v-model="form.time"
              show-time
              type="date"
              valueFormat="YYYYMMDD"
              format="YYYYMMDD"
              placeholder="请选择"
            />
          </a-form-model-item>
        </a-form-model-item>
        <a-divider />

        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button v-if="type==1" type="primary" @click="handleSubmit">打印</a-button>
          <template v-if="type==2">
            <a-button type="primary" @click="handleSubmit">废除</a-button>
            <div style="color: red;">一旦确认作废，无法撤回，请仔细检查需作废优惠券号！</div>
          </template>
          <template v-if="type==3">
            <a-button type="primary" @click="handleSubmit">保存</a-button>
            <div style="color: red;">一旦确认延期，无法撤回，请仔细检查需延期优惠券号！</div>
          </template>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>
<script>
  import { vouchersCheck, voucherDelay, voucherCancel, printDetails} from '@/api/headquartersCoupon/index'
  import Header from '@/views/box/components/layouts/Header'
  export default {
    components: {
      Header
    },
    data() {
      return {
        type: this.$route.query.type,
        spinning: false,
        form: {
          reason: '',
          relationList: [
            {
              vouchersNoStart: '',
              vouchersNoEnd: ''
            }
          ]
        },
        rules: {
          time: [
            { required: true, message: '请选择', trigger: 'change'}
          ],
          reason: [
            { required: true, message: '请填写', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      token() {
        return this.$route.query.token
      },
      subTitle() {
        // 1.补打印 2.作废 3.延期-
        const subTitleList = ['优惠券补打印/连续添加', '添加需作废的优惠券号/连续添加', '优惠券延期/连续添加']
        return subTitleList[this.type - 1]
      }
    },
    watch: {
    },
    activated() {
    },
    created() {
    },
    mounted() {
    },
    methods: {
      // 添加新的批次
      handleAdd() {
        this.form.relationList.push(
          {
            vouchersNoStart: '',
            vouchersNoEnd: ''
          }
        )
      },

      // 废除
      handleDelet(index) {
        this.form.relationList.splice(index, 1)
      },

      // 检测券号
      check(vouchersNoStart, vouchersNoEnd) {
        return new Promise((resolve, reject) => {
          const data = {
            startNo: vouchersNoStart,
            endNo: vouchersNoEnd
          }
          vouchersCheck(data).then(res => {
            if (res.code == 200) {
              resolve()
            } else {
              reject()
            }
          }).catch((err) => {
            reject()
          });
        });
      },
      

      handleSubmit() {
        this.$refs.rulesForm.validate(async valid => {
          if (valid) {
            this.spinning = true
            const relationList = this.form.relationList
            for (let i = 0; i < relationList.length; i++) {
              try {
                await this.check(relationList[i].vouchersNoStart, relationList[i].vouchersNoEnd)
              } catch (e) {
                this.$message.info(`批次${i+1}未检测到当前优惠券号，请仔细核对填写信息！`)
                 this.spinning = false
                return
              }
            }
            const pageId = this.$route.query.pageId
            const { time, reason } = this.form
            // 1.补打印 2.作废 3.延期
            const data = {
              pageId,
              token: this.token,
              list: this.form.relationList,
              validDate: time,
              reason
            }
            if (this.type == 1) {
              printDetails(data).then(res => {
                this.spinning = false
                if (res.code === 200) {
                  const data = decodeURIComponent(JSON.stringify(res.data))
                  this.$router.push(`/headquarters-coupon/print/1?data=${data}`)
                } else {
                  this.$message.warning(res.msg || res.message)
                }
              }).catch(err => {
                this.spinning = false
              })
              return
            }
            const submitApi = this.type == 2 ? voucherCancel : voucherDelay
            submitApi(data).then(res => {
              this.spinning = false
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.$message.warning(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      }
    }
  }
</script>
<style scoped>
  .association-list /deep/td{
    padding-bottom: 0 !important;
  }
  .hidden-title  /deep/.ant-form-item-label > label{
    visibility: hidden;
  }
</style>
